// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    env: "yiliaojiufeng-6gt0kj1l1df8b7b7",
    traceUser: true,
})

const time_format = (time) => {
    if (time.toString().length == 13) {
        var tme = new Date(time);
    } else {
        var tme = new Date(time * 1000);
    }
    var Y = tme.getFullYear();
    var M = (tme.getMonth() + 1 < 10 ? '0' + (tme.getMonth() + 1) : tme.getMonth() + 1);
    var D = tme.getDate();
    var h = tme.getHours();
    var m = tme.getMinutes();
    var tem1 = Y + '-' + M + '-' + D + ' ' + h + ':' + m;
    console.log(tem1);
    return tem1;
}

// 云函数入口函数
const db = cloud.database()

exports.main = async (event, context) => {
    var newsDetail = {}
    var isStar = 0
    var readCount = ''
    var time = ''
    var html = ''
    const wxContext = cloud.getWXContext()
    //获取文章信息
    await db.collection('news_article').where({
        _id: event.newsId
    }).limit(1).get().then(res => {
        newsDetail = res.data[0]
        time = time_format(res.data[0]._createTime)
        html = res.data[0].richText.replace(/<p/ig, '<p class="p_class"')
    })
    //获取是否收藏
    await db.collection('user_Star').where({
        _openid: wxContext.OPENID,
        newsId: event.newsId
    }).count().then(res => {
        isStar = res.total
    })
    //获取阅读次数
    await db.collection('readHistory').where({
        newsId: event.newsId
    }).count().then(res => {
        readCount = res.total + ' 阅读'
    })


      //获取评论信息
  var commentCount = await db.collection("comment").where({
    artId: event.newsId
  }).count()
  var commentListRaw = await db.collection("comment").where({
    artId: event.newsId
  }).limit(2).get()
  var result = []
  for (var i = 0; i < commentListRaw.data.length; i++) {
    var temp = {}
    var userInfo = await db.collection("user").where({
      _openid: commentListRaw.data[i].openid
    }).get();
    console.log(commentListRaw.data[i].time)
    temp = {
      commentInfo: commentListRaw.data[i],
      userInfo: userInfo.data[0],
      time: time_format(commentListRaw.data[i].time)
    }
    result.push(temp)
  }

    return {
        isStar: isStar,
        readCount: readCount,
        time: time,
        mainpic: newsDetail.mainpic,
        title: newsDetail.title,
        writer: newsDetail.writer,
        _id: newsDetail._id,
        video: newsDetail.video,
        html: html,
        commentCount,
        commentDesc: result
    }
}